#include "Explosion.h"
#include <iostream>


Explosion::Explosion(void)
{
	frame_count = 0;
	current_cell = 0;

	explosion_tex.loadFromFile("art/explosion.png");
	// Create a sprite
	explosion.setTexture(explosion_tex);

	////sprite.setTextureRect(sf::IntRect(10, 10, 50, 30));
	explosion.setTextureRect(sf::IntRect(0, 0, 64, 64));
	explosion.setColor(sf::Color(255, 255, 255, 255));
	explosion.setPosition(76, 50);
	exploding = false;

	explSndBuffer.loadFromFile("sound/explode.wav");
	explSound.setBuffer(explSndBuffer);
	explSound.setVolume(50);


}


Explosion::~Explosion(void)
{
}

void Explosion::update()
{
	if(!exploding && explSound.getStatus() != sf::SoundSource::Playing)
	{
		int y_dist = 0 + (std::rand() % (int)(750 - 0 + 1));

		int number = 0 + (std::rand() % (int)(1000 - 0 + 1));

		if(number > 996 && number < 998)
		{
			exploding = true;
			//shake screen
			explSound.play();
			int y_off = y_dist;

			explosion.setPosition(76, y_off);
		}
		else if(number > 998)
		{
			exploding = true;
			int y_off = y_dist;
			
			//shake screen
			explSound.play();
			
			explosion.setPosition(884, y_off);
		}
	}	
	if(explSound.getStatus() == sf::SoundSource::Stopped){
		exploding = false;
	}
}

void Explosion::render(sf::RenderWindow* w)
{
	if (exploding)
	{	
		if(frame_count > 5)
		{
			if (current_cell < 26)
			{
				int height;
				if(current_cell == 0)
				{
					height = 0;
				}
				else
				{
					height = current_cell / 5;
				}
				
				int width = current_cell - (height * 5);
				explosion.setTextureRect(sf::IntRect(width * 64, height * 64, 64, 64));
				current_cell++;
			}
			else
			{
				current_cell = 0;
				exploding = false;
			}
			frame_count = 0;
		}
		else
		{
			frame_count ++;
		}
		w->draw(explosion);
	}
}
